<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/6
 * Time: 14:29
 */

namespace app\admin\controller;


use app\admin\common\Base;
use think\facade\Request;
use think\Facade\Session;

class User extends Base
{
    public function userList(){
        $condition = [];
        if (Session::get('is_admin') != 1){
            $condition[] = ['id', '=', Session::get('admin_id')];
        }
        $userList = \app\admin\model\User::all(function ($query) use($condition){
            $query->field('id,name,email,mobile,create_time,is_admin,status')->where($condition);
        });
        $this->assign('userList', $userList);
        return $this->view->fetch('userlist');
    }

    public function userEdit(){
        $id = Request::param('id');
        if (empty($id)){
            return $this->error('非法访问');
        }
        $user = \app\admin\model\User::get($id)->toArray();
        if (empty($user)){
            return $this->error('非法访问');
        }
        $this->assign('userInfo',$user);
        return $this->view->fetch('useredit');
    }

    public function doEdit(){
        if ( ! Request::isPost()){
            return $this->error('非法访问');
        }
        $data = Request::post();
        $id = $data['id'];
        if (empty($data['password'])){
            unset($data['password']);
        }else{
            $data['password'] = sha1($data['password']);
        }
        unset($data['id']);
        $res = \app\admin\model\User::where('id',$id)->update($data);
        if ($res){
            return $this->success('更新成功','userList');
        }
        return $this->error('没有更新或更新失败，请稍后再试');
    }

    public function doDelete(){
        $id = Request::param('id');
        if (empty($id)){
            return $this->error('非法访问');
        }
        if (\app\admin\model\User::where('id',$id)->delete()){
            return $this->success('删除成功', 'userList');
        }
        return $this->error('删除失败，请稍后再试');
    }

    public function logout(){
        Session::clear();
        return $this->success('退出成功','login/index');
    }
}